﻿/*
SafeGrid Module 

Module intended for use with liteGrid and JEditable to encode
data before it is persisted (and rendered) in order
to prevent injection of javascript within pages using 
liteGrid, while decoding it prior to edits to leave data appearing
as it should to the user. This is not intended as a stand-alone solution to javascript
injection, and should only be used alongside proper server-side protection
measures. 

Author: David Koehler
DateAuthored: 8/4/2009
*/

function SafeGridModule() {

    var base = this;

    base.initialize = function(liteGrid, options) {
        base.liteGrid = liteGrid;
        base.options = options;

        //Make sure that JEditable is in use. This module responds to it!
        if (!$.editable) {
            console.log("Error: JEditable is required for use with this module!");
        }

        liteGrid.$el.bind("valueChanged", base.valueChanged);
        liteGrid.$el.bind("cellEditing", base.cellEditing);
    }

    base.valueChanged = function(event) {
		event.newValue = base.htmlEncode(event.newValue);
    }

    base.cellEditing = function(event) {
		event.currentValue = base.htmlDecode(event.currentValue);
    }

    base.htmlEncode = function(value) {
	    return $('<div/>').text(value || "").html();
	}

	base.htmlDecode = function(value) {
		return $('<div/>').html(value || "").text();
	}
}
